<?php
/*
 *      sans titre
 *
 *      Copyright 2010 Patrice Ferlet <metal3d@gmail.com>
 *
 *      This program is free software; you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or
 *      (at your option) any later version.
 *
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *
 *      You should have received a copy of the GNU General Public License
 *      along with this program; if not, write to the Free Software
 *      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 *      MA 02110-1301, USA.
 */

// $Id: log.class.php 22 2010-12-15 10:11:10Z Metal3d $
// $HeadURL: http://valaya.googlecode.com/svn/trunk/utils/log.class.php $

/**
 *  A simple class to log everything in files, firebug, etc...
 * */
class Log {

	const LOG=0;
	const INFO=1;
	const WARN=2;
	const ERROR=3;

	/**
	 * Write log, level are Log::LOG, Log::INFO, Log::WARN and Log::ERROR
	 *
	 * @param string $title
	 * @param mixed $message
	 * @param int $level
	 * */
	public function write($title='',$message,$level=self::LOG){
		$type = _config('logtype','project');
		if(is_null($type)) return;
		switch ($level) {
			case self::ERROR:
				$f = "error"; break;
			case self::WARN:
				$f = "warn"; break;
			case self::INFO:
				$f = "info"; break;
			case self::LOG:
			default:
				$f = "log";
					
		}


		
		if(strlen($title)>0) $title = '['.$title.'] ';
		$title .= gettype($message) ;
		switch ($type) {
			case 'firebug':
				$message = json_encode($message);
				$obj = new stdClass();
				$obj->head.='<script>try{console.'.$f.'("'.$title.'","--file--",--line--,'.$message.');}catch(e){}</script>';
				try{
					throw new LogException($obj);
				}catch (LogException $e){
					//Do Nothing !!! Log is ok
					$tr = $e->getTrace();
					$e->msg->head = str_replace('--file--',
					$tr[0]['file']
					,$e->msg->head);

					$e->msg->head = str_replace('--line--',
					$tr[0]['line']
					,$e->msg->head);
					if(!Project::isDisplayed()){
						$c = &Project::getContent();
						if(strlen($c)>0){
							$c = str_replace('</head>',$e->msg->head.'</head>',$c);
						}
						else
						Template::getMain()->head.=$e->msg->head;
					} else {
						echo $e->msg->head;
					}
				}
				break;
			case 'file':
				break;
			case 'none':
				break;
			case 'dump':
			default:
				break;
		}
	}

}

class LogException extends Exception{
	public $msg;
	public function __construct($message) {
		$this->msg = $message;
	}
}
